package twentytwentyone_3;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2021-03-05 16:32
 * @Modified By:
 */
public class LicenseKeyFormatting_482 {
    public static void main(String [] args){
        String S = "-";
        System.out.println(licenseKeyFormatting(S, 2));
    }

    public static String licenseKeyFormatting(String S, int K) {
        if(S == "" || S == "-"){
            return "";
        }
        if (S.length() == 1){
            return S.toUpperCase();
        }
        String bigAndOldStr = S.toUpperCase();
        char[] bigAndOldStrChars = bigAndOldStr.toCharArray();
        int count = 0;
        StringBuilder bigAndNewStr = new StringBuilder();
        StringBuilder result = new StringBuilder();
        for (char bigAndOldStrChar : bigAndOldStrChars) {
            if (bigAndOldStrChar == '-'){
                continue;
            }else {
                bigAndNewStr.append(bigAndOldStrChar);
            }
        }
        int length = bigAndNewStr.length();
        int first = length % K;
        char[] bigAndNewStrChars = bigAndNewStr.toString().toCharArray();
        for (int i = 0; i < length; i++) {
            if (first == 0){
                count ++;
                result.append(bigAndNewStrChars[i]);
                if (count % K == 0 && i != length - 1){
                    result.append('-');
                }
            }else {
                if (i < first){
                    result.append(bigAndNewStrChars[i]);
                    if (i == first - 1){
                        result.append('-');
                    }
                }else {
                    count ++;
                    result.append(bigAndNewStrChars[i]);
                    if (count % K == 0 && i != length - 1){
                        result.append('-');
                    }
                }
            }
        }
        return result.toString();
    }
}
